/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.common  
 */
package com.apache.bid.common;

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.apache.uct.common.ToolsUtil;

/**
 * description: 过滤关键字 
 * @author Hou Dayu 创建时间：2016-5-10  
 * 
 */
public class KeywordFilter {

	private static Pattern pattern = null;
	private static KeywordFilter filter = new KeywordFilter();
	private Long lastTime = 0l;
	private String filePath = "";

	public static KeywordFilter getInstance() {
		return (null == filter) ? new KeywordFilter() : filter;
	}

	private KeywordFilter() {
		filePath = ToolsUtil.getClassLoaderPath() + "config/keyword.properties";
		init();
	}

	private void init() {
		try {
			File oldfile = new File(filePath);
			long lastModletime = oldfile.lastModified();
			if (0 == lastTime || lastTime < lastModletime) {
				lastTime = lastModletime;
				StringBuilder stringBuilder = new StringBuilder();
				Properties pro = new Properties();
				FileInputStream fileInput = new FileInputStream(filePath);
				pro.load(fileInput);
				Enumeration<?> enu = pro.propertyNames();
				while (enu.hasMoreElements()) {
					stringBuilder.append(enu.nextElement() + "|");
				}
				stringBuilder.deleteCharAt(stringBuilder.length() - 1);
				pattern = Pattern.compile(new String(stringBuilder.toString().getBytes("ISO-8859-1"), "UTF-8"));
				if (pro != null) {
					fileInput.close();
					pro = null;
				}
			}
			oldfile = null;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public String doFilter(String str) {
		init();
		Matcher m = pattern.matcher(str);
		str = m.replaceAll("***");
		return str;
	}

	public String doFilter(String str, String with) {
		init();
		Matcher m = pattern.matcher(str);
		str = m.replaceAll(with);
		return str;
	}
}
